package cn.gdchent.springbootsecurity.service.impl;


import cn.gdchent.springbootsecurity.configbean.SecurityUserDetailsServiceBean;
import cn.gdchent.springbootsecurity.enity.UserInfoDetails;
import cn.gdchent.springbootsecurity.enums.ResultStatusEnum;
import cn.gdchent.springbootsecurity.mapper.UserMapper;
import cn.gdchent.springbootsecurity.response.HttpResultMap;
import cn.gdchent.springbootsecurity.service.RegisterService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SecurityUserDetailsServiceBean securityUserDetailsServiceBean;

    @Override
    public HttpResultMap register(UserInfoDetails userInfoDetails) {

        String userName= userInfoDetails.getUsername();
        //先判断用户名是否已经存在
        UserInfoDetails dbUserInfoDetails =userMapper.findByUserName(userName);
        if(dbUserInfoDetails ==null){
            JSONObject jsonObject=new JSONObject();
            String userId= UUID.randomUUID().toString();
            String password=securityUserDetailsServiceBean.passwordEncoder().encode(userInfoDetails.getPassword());
            StringBuilder stringBuilder=new StringBuilder();
            for(int i=0;i<userInfoDetails.getAuthorities().size();i++){
                List<? extends GrantedAuthority> grantedAuthorities= (List<? extends GrantedAuthority>) userInfoDetails.getAuthorities();
                if(i==userInfoDetails.getAuthorities().size()-1){
                    stringBuilder.append(grantedAuthorities.get(i));
                }else{
                    stringBuilder.append(grantedAuthorities.get(i)).append(",");
                }

            }
            String authority=stringBuilder.toString();
            Integer row=userMapper.insertUser(userId, userInfoDetails.getUsername(),password,authority);
            jsonObject.put("row",row);
            return new HttpResultMap(
                    ResultStatusEnum.SUCCESS.getStatus(),
                    ResultStatusEnum.SUCCESS.getMsg(),
                    jsonObject
            );
        }
        return new HttpResultMap(
                ResultStatusEnum.USER_ALREADY.getStatus(),
                ResultStatusEnum.USER_ALREADY.getMsg(),
                new JSONObject()
        );
    }
}
